package com.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.sys.entity.SysCrontab;
import com.sys.service.SysCrontabService;
import com.sys.utils.Utils;
import com.bhudy.base.QueryFilter;
import com.bhudy.enums.Relation;
import com.bhudy.exception.SysException;
import com.bhudy.exception.SysExceptionCode;
import com.bhudy.utils.ResponseResult;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author bhudy
 * @description SysCrontabController
 * @date Mon Nov 04 14:28:07 CST 2019
 */
@RestController
public class SysCrontabController {
    @Autowired
    private SysCrontabService sysCrontabService;


    /**
     * 获取sysCrontab表的数据
     *
     * @param page  页数{1}
     * @param limit 显示数量{10}
     * @return sysCrontab的list
     */
    @GetMapping(value = "/api/v1/sysCrontabs")
    public ResponseResult getAll(Integer page, Integer limit, String name) {
        QueryFilter queryFilter = new QueryFilter().and("status", Relation.NOT_EQUAL, 1);
        if (name != null && !name.equals("")) {
            queryFilter.andLike("name", "%" + name + "%");
        }
        if (page != null && limit != null) queryFilter.limit(--page, limit);
        return ResponseResult.printMapJson(0, sysCrontabService.count(queryFilter), sysCrontabService.findList(queryFilter));
    }

    @GetMapping(value = "/api/v1/sysCrontab")
    public ResponseResult get(Long id) {
        return ResponseResult.printMapJson(0, sysCrontabService.get(id));
    }

    @PostMapping(value = "/api/v1/sysCrontab")
    public ResponseResult insert(@RequestBody String json) {
        return ResponseResult.printMapJson(0, sysCrontabService.insert(JSONObject.parseObject(json, SysCrontab.class)));
    }

    @PutMapping(value = "/api/v1/sysCrontab")
    public ResponseResult update(@RequestBody String json) {
        return ResponseResult.printMapJson(0, sysCrontabService.update(JSONObject.parseObject(json, SysCrontab.class)));
    }

    @DeleteMapping(value = "/api/v1/sysCrontabs")
    public ResponseResult delete(@RequestBody String json) {
        return ResponseResult.printMapJson(0, sysCrontabService.delete(JSONObject.parseObject(json, Long[].class)));
    }

    @GetMapping(value = "/api/v1/removeQuartzJob")
    public ResponseResult removeQuartzJob(Long id) {
        try {
            sysCrontabService.removeQuartzJob(id);
            return ResponseResult.printMapJson();
        } catch (SchedulerException e) {
            Utils.loggerError(getClass(), e);
            throw new SysException(SysExceptionCode.CODE_40005, e.getMessage());
        }
    }

}
